<template>
  <div class="zero-recommend">
    <div class="addprogram">
      <el-button type="primary" @click="addCard = true; addCardData = {}">新增分类</el-button>
    </div>

    <!-- 新增分类 -->
    <el-dialog :visible.sync="addCard" title="新增首页推荐课程" width="500px">
      <el-form ref="createInfo" :model="addCardData" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="分类名称" prop="title">
          <el-input v-model="addCardData.title" placeholder="推荐精品" style="width:260px"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="排序" prop="weight">
          <el-input v-model="addCardData.weight" placeholder="大于零的整数，越小越靠前" style="width:260px"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="首推课程编号" prop="lesson">
          <el-input v-model="addCardData.lesson" placeholder="输入课程编号，如123" style="width:260px"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="首推课程图片">
          <img v-if="addCardData.picture" :src="addCardData.picture" alt style="width: 270px">
          <el-upload
            :limit="1"
            :on-change="fileChange"
            :http-request="upLoadFile"
            class="upload-demo"
            action=""
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">推荐270*412</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="其他课程的编号" prop="otherLesson">
          <el-input v-model="addCardData.otherLesson" placeholder="123,516,213" style="width:260px"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="更多按钮链接" prop="url">
          <el-input v-model="addCardData.url" placeholder="http://www.abc.com" style="width:260px"/>
          <br><span v-if="message" style="color: red">&nbsp;&nbsp;{{ message }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveInfo">保 存</el-button>
      </div>
    </el-dialog>

    <subtable
      :table-label="zeroLabel"
      :table-data="zeroData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="button" :min-width="20" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            type="primary"
            @click="handleClickEdit(scope.row)"
            @command="handleCommand($event,scope.row)"
          >编辑
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </subtable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
  </div>
</template>

<script>
import Subtable from '@/components/Eltable'
import Tinymce from '@/components/Tinymce'
import Pagination from '@/components/Pagination' // 分页组件
import { upLoadFile } from '@/api/upLoadFile' // 数据接口
import { getRecommendedCoursesList, updateRecommend, addRecommend, deleteRecommend } from '@/api/operate/zerotheme' // 数据接口
import { getTenantId } from '@/utils/auth'
export default {
  components: {
    Subtable,
    Tinymce,
    Pagination
  },
  data() {
    return {
      reg: /^((https|http|ftp|rtsp|mms){0,1}(:\/\/){0,1})(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/,
      message: '',
      formLabelWidth: '140px',
      total: 0,
      currentpage: 1,
      pagesize: 10,
      addCard: false,
      addCardData: {
        title: '',
        weight: '',
        lesson: '',
        fileId: '',
        picture: '',
        otherLesson: '',
        url: '',
        file: ''
      },
      zeroLabel: [
        {
          label: '分类名称',
          width: '20',
          prop: 'title'
        },
        {
          label: '排序',
          width: '10',
          prop: 'weight'
        },
        {
          label: '首推课程',
          width: '10',
          prop: 'lesson'
        },
        {
          label: '其他课程',
          width: '10',
          prop: 'otherLesson'
        },
        {
          label: '创建时间',
          width: '10',
          prop: 'createTimeStr'
        }
      ],
      rules: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        lesson: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        otherLesson: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      zeroData: [],
      listFilter: []
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    handleClickEdit(row) {
      this.addCardData = Object.assign({}, row)
      this.addCard = true
    },
    handleCommand(command, row) {
      if (command === '1') {
        this.$confirm('确认要删除该推荐课程', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRecommend(row.id).then(res => {
            this.$notify({
              title: '成功',
              message: '推荐课程已删除',
              type: 'success',
              duration: 2000
            })
            this.getData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消'
          })
        })
      }
    },
    handleSizeChange(val) {
      console.log(val)
      this.currentpage = 1
      this.pagesize = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      console.log(val)
      this.currentpage = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    getData() {
      getRecommendedCoursesList().then(response => {
        this.zeroData = response.data.items.filter(item => {
          if (item.tenantId !== getTenantId()) return false
          return true
        })
        this.zeroData.map(item => {
          item.createTimeStr = new Date(item.createTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
        })
        this.total = this.zeroData.length
        this.listFilter = this.zeroData
      })
    },
    fileChange(file) {
      this.addCardData.file = file.raw
    },
    upLoadFile() {
      const form = new FormData()
      form.append('name', this.addCardData.file.name)
      form.append('uid', this.addCardData.file.uid)
      form.append('file', this.addCardData.file)
      upLoadFile(form).then(response => {
        this.addCardData.picture = response.data.url
        this.addCardData.fileId = response.data.id
      })
    },
    saveInfo() {
      this.$refs.createInfo.validate((valid) => {
        if (valid) {
          this.addCard = false
          if (this.addCardData.url && !this.reg.test(this.addCardData.url)) {
            this.message = '输入的值并不是一个合法的网址，请重新输入！'
            return
          } else {
            this.message = ''
          }
          if (this.addCardData.id) {
            updateRecommend(this.addCardData).then(res => {
              this.$notify({
                title: '成功',
                message: '修改推荐课程完成',
                type: 'success',
                duration: 2000
              })
              this.getData()
            })
          } else {
            this.addCardData.tenantId = getTenantId()
            addRecommend(this.addCardData).then(res => {
              this.$notify({
                title: '成功',
                message: '新增推荐课程成功！',
                type: 'success',
                duration: 2000
              })
              this.getData()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.zero-recommend {
  .el-dialog {
    border-radius: 6px;
  }
  .addprogram {
    width: 100%;
    padding: 0 0 21px 0;
    height: 36px;
    .el-button {
      float: right;
    }
  }
}
</style>
